<?php

namespace Addons\Zmphoto\Controller;
use Addons\Zmphoto\Controller\BaseController;

class ZmphotoController extends BaseController{
	function _initialize() {
		parent::_initialize();
	}

    public function lists(){
    	$imputbtn['url'] = U('impData',array('aid'=>I('aid')));
		$imputbtn['title'] = '导入用户数据';
		$morebtn[] = $imputbtn;
		$this->assign('top_more_button',$morebtn);
		$list_data = $this->_get_model_list($this->getModel('photo_zm_activity'));
		
		$this->assign ( $list_data );
		$this->display();
	}


    
    public function exportExcel($expTitle,$expCellName,$expTableData){
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName = $_SESSION['account'].date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        
        vendor ( "PHPExcel" );
          
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
        
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
       // $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));  
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]); 
        } 
          // Miscellaneous glyphs, UTF-8   
        for($i=0;$i<$dataNum;$i++){
          for($j=0;$j<$cellNum;$j++){
            $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
          }             
        }  
        
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  
        $objWriter->save('php://output'); 
        exit;   
 }
/**
     *
     * 导出Excel
     */
    public function expData(){//导出Excel
    	$id = I('get.id');
        $xlsName  = "UserData";
        $xlsCell  = array(
        array('id','序列'),
        array('no','学号'),
        array('department','学院'),
        array('major','专业'),
        array('class','班级'),
        array('username','姓名'),   
        array('photo_url','图片地址'),        
        );
        $xlsModel = M('PhotoZmData');
        $map['id'] = $id;
        $map['status'] = 1;
        $map['confirm'] = 1;
        $xlsData  = $xlsModel->field('id,no,department,major,class,username,photo_url')->where($map)->order('department DESC')->select();
        foreach ($xlsData as $k => $v)
        {
            $xlsData[$k]['photo_url']= get_file_url($xlsData[$k]['photo_url']);
        }
        $this->exportExcel($xlsName,$xlsCell,$xlsData);
         
    }
    
    /*导入用户数据*/
    function impData(){
    	if(IS_POST){
    		$aid = I('post.aid',0,'intval');
    		$map['id'] = $aid;
    		$map['status'] = 1;
    		$map['token'] = get_token();
    		if(!$aid || ! M('photo_zm_activity')->field('id,actname')->where($map)->find())   $this->error('请选择活动');

    		if (!empty($_FILES)) {
            $upload = new \Think\Upload();// 实例化上传类
			$upload->maxSize = 3145728 ;// 设置附件上传大小
			$upload->exts = array('xlsx', 'xls');// 设置附件上传类型
			$upload->savePath = ''; // 设置附件上传目录
			$upload->replace = true; // 覆盖文件
			// 单文件上传
			$info = $upload->uploadOne($_FILES['field']);
			if(!$info) {
			// 上传错误提示错误信息
			$this->show($upload->getError());
			}
                vendor("PHPExcel");
                $file_name='./Uploads/'.$info['savepath'].$info['savename'];
                $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
                $objPHPExcel = $objReader->load($file_name,$encode='utf-8');
                $sheet = $objPHPExcel->getSheet(0);
                $highestRow = $sheet->getHighestRow(); // 取得总行数
                $highestColumn = $sheet->getHighestColumn(); // 取得总列数
                $arr = array();
                $token = get_token();
                $time = time();
                for($i=2;$i<=$highestRow;$i++)
                {   
                   $data['aid'] = $aid;
                   $data['token'] = $token;
                   $data['no'] = $objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue();  
                   $data['card_id'] = $objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue();  
                   $data['department'] = $objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue();
                   $data['major'] = $objPHPExcel->getActiveSheet()->getCell("D".$i)->getValue();
                   $data['grade'] = $objPHPExcel->getActiveSheet()->getCell("E".$i)->getValue();
                   $data['class'] = $objPHPExcel->getActiveSheet()->getCell("F".$i)->getValue();
                   $data['password'] = $objPHPExcel->getActiveSheet()->getCell("G".$i)->getValue();
                   $data['username'] = $objPHPExcel->getActiveSheet()->getCell("H".$i)->getValue();
                   $data['mobile'] = $objPHPExcel->getActiveSheet()->getCell("I".$i)->getValue();
                   $arr[] = $data;
                } 
                 M('PhotoZmData')->addAll($arr);
                 $this->success('导入成功!',U('lists'));
        }else
            {
                $this->error("请选择上传的文件");
            } 
    	}else{
    		$this->assign('actData',M('photo_zm_activity')->field('id,actname')->where(array('status'=>1,'token'=>get_token()))->select());
    		$this->display();
    	}   
}


	function preview(){
		$id = I ( 'id', 0, 'intval' );
		$url = addons_url( 'Zmphoto://Wap/index/id/'.$id);
		$this -> assign('url',$url);
		$this->display ( SITE_PATH . '/Application/Home/View/default/Addons/preview.html' );
	}


      /*学生二维码*/
    public function showCode(){
        $aid = I('get.id',0,'intval');
        $save_path = isset($_GET['save_path'])?$_GET['save_path']:'qrcode/';  //图片存储的绝对路径
        $web_path = isset($_GET['save_path'])?$_GET['web_path']:'qrcode/';        //图片在网页上显示的路径
        $qr_data = isset($_GET['qr_data'])?$_GET['qr_data']:addons_url('Zmphoto://Wap/photoRe',array('aid'=>$aid));
        $qr_level = isset($_GET['qr_level'])?$_GET['qr_level']:'H';
        $qr_size = isset($_GET['qr_size'])?$_GET['qr_size']:'10';
        $save_prefix = isset($_GET['save_prefix'])?$_GET['save_prefix']:'ZETA';
        if($filename = $this->createQRcode($save_path,$qr_data,$qr_level,$qr_size,$save_prefix)){
            $pic = $web_path.$filename;
        }
        echo "<img src='{$pic}' style='text-align:center'/>";
    }

    /*数据分析*/
    public function fen(){
        $aid = I('get.id',0,'intval');
        $adata = M('photo_zm_activity')->find($aid);
        $this->assign('adata',$adata);  //活动信息
        /*获取活动总完成情况*/
        $arr = M('photo_zm_data')->field("count('confirm') as confirm,confirm as status")->where(array('aid'=>$aid,'token'=>get_token()))->group('confirm')->select();
        $this->assign('arr',$arr);
        /*获取各班的数据*/
        $s = M('photo_zm_data')->field("count('confirm') as confirm,class,confirm as status")->where(array('aid'=>$aid,'token'=>get_token()))->group('class,confirm')->select();
        $classData = array();
        $num = count($s);
        for($i=0;$i<$num;$i++){
            $classData[$s[$i]['class']][$s[$i]['status']] = $s[$i]['confirm'];
        }
        $this->assign('classData',$classData);
        $this->display();
    }


    /*无手机端入口*/
    public function noMobile(){
        $aid = I('get.id');
        $where['aid'] = $aid;
        if(IS_POST){
            $model = D('Addons://Zmphoto/PhotoZmData');  
            if($info = $model->create()){
                $where['aid'] = $aid;
                $where['card_id'] = $info['card_id']; 
                if(! $s = $model->getOne($where)) $this->error('身份证号码输入错误!');
                // if($s['openid']) $this->error('当前身份证已经绑定用户');
                if($model->update($where,array('update_time'=>time(),'mobile'=>$info['mobile']))){
                  $this->success('进入成功',U('studInfo',array('aid'=>$aid,'sid'=>$s['id'])));
                }else{
                    $this->error('请重新绑定!');
                }
            }else{
                $this->error($model->getError());
            }
        }else{
            $this->display();
        }
    }

    /*用户信息展示*/
    public function studInfo(){
        $aid = I('get.aid');
        $sid = I('get.sid');
        /*修改*/
        $s['is_tag'] = 1;
        $s['is_pay'] = 1;
        $s['pay_time'] = time();
        D('Addons://Zmphoto/PhotoZmData')->update(array('id'=>$sid,'aid'=>$aid,'token'=>get_token()),$s);
        /*展示用户数据*/
        $sdata = M('photo_zm_data')->where(array('id'=>$sid))->find();
        $this->assign('sdata',$sdata);
        /*生成用户二维码*/
        $save_path = isset($_GET['save_path'])?$_GET['save_path']:'qrcode/';  //图片存储的绝对路径
        $web_path = isset($_GET['save_path'])?$_GET['web_path']:'qrcode/';        //图片在网页上显示的路径
        $qr_data = isset($_GET['qr_data'])?$_GET['qr_data']:addons_url('Zmphoto://Wap/studPhoto',array('aid'=>$aid,'uid'=>$sid));
        $qr_level = isset($_GET['qr_level'])?$_GET['qr_level']:'H';
        $qr_size = isset($_GET['qr_size'])?$_GET['qr_size']:'10';
        $save_prefix = isset($_GET['save_prefix'])?$_GET['save_prefix']:'ZETA';
        if($filename = $this->createQRcode($save_path,$qr_data,$qr_level,$qr_size,$save_prefix)){
            $pic = $web_path.$filename;
        }
        $this->assign('pic',$pic);
        $this->display();
    }

    /*修改信息*/
    public function updateInfo(){
        $aid = I('get.aid');
        $sid = I('get.sid');
        if(IS_POST){
           $model = D('Addons://Zmphoto/PhotoZmData');  
           $mobile = I('post.mobile');
           $no = I('post.no');
           $class = I('post.class');
           if(!$mobile) $this->error('请输入手机号码');
           if(!$no) $this->error('请输入学号');
           if(!$class) $this->error('请输入班级');
           if(!preg_match('/^0?(13|14|15|17|18)[0-9]{9}$/',$mobile)) $this->error('手机号码格式错误！');
           if($model->update(array('id'=>$sid),array('mobile'=>$mobile,'no'=>$no,'class'=>$class))){
                $this->success('修改成功!',U('studInfo',array('aid'=>$aid,'sid'=>$sid)));
           }else{
                $this->error('请重新确定');
           }
        }else{
            $this->assign('isupdate',1);
            $this->display('noMobile');
        }
    }


    /*支付界面*/
    public function payUi(){
        $this->display();
    }

    /*改变用户支付状态*/
    public function sendPay(){
        $url = I('post.url');
        $arr = explode('/', $url);
        $aid = $arr[array_search('aid', $arr)+1];
        $uid = (int) $arr[array_search('uid', $arr)+1];
        $model = D('Addons://Zmphoto/PhotoZmData'); 
        $data  = D('Addons://Zmphoto/PhotoZmData')->getOne(array('id'=>$uid,'aid'=>$aid,'token'=>get_token())); 
        if($data['is_pay']){
            $mes['status'] = 0;
            $mes['mess'] = '当前用户已经支付';
        }else{
            $info['is_pay'] = 1;
            $info['pay_time'] = time();
            if(!$model->update(array('id'=>$uid,'aid'=>$aid,'token'=>get_token()),$info)){
                 $mes['status'] = 0;
                 $mes['mess'] = '支付失败，请重新扫描';
            }else{
                $mes['status'] = 1;
                $mes['mess']   = '支付成功';
                $data['pay_time'] = date("Y-m-d H:i",$data['pay_time']);
                $mes['data']   = $data;
            }
        }
        $this->ajaxReturn($mes);
    }

}


